<template>
  <div id="panel">
    <el-row :gutter="20">
      <el-col :span="24" class="body-container">
        <el-card class="queryForm">
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            label-width="150px"
          >
            <el-form-item label="时间范围">
              <el-date-picker
                v-model="dateRange"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="污染源">
              <ElTreeSelect
                :data="treeData"
                v-model="selectedNodeId"
                @change="handleChange"
                placeholder="请选择节点..."
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
                >搜索</el-button
              >
              <el-button
                icon="el-icon-refresh"
                size="mini"
                @click="handleExport"
                >导出</el-button
              >
            </el-form-item>
          </el-form>
          <div class="data-content">
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5" style="float: right">
                <el-radio-group
                  v-model="viewType"
                  class="view-filter"
                  @change="handleViewChange"
                >
                  <el-radio label="table">表格</el-radio>
                  <el-radio label="chart">图表</el-radio>
                </el-radio-group>
              </el-col>
            </el-row>
            <!-- 表格视图：带分页控件 -->
            <div
              v-if="viewType === 'table'"
              class="table-container"
              key="table-view"
            >
              <el-table
                id="selectTable"
                :height="tableHeight - 60"
                :data="paginatedData"
                border
                style="width: 100%"
              >
                <el-table-column
                  v-for="column in tableOp"
                  :key="column.prop"
                  :prop="column.prop"
                  :label="column.label"
                  align="center"
                >
                  <template slot-scope="scope">
                    <span
                      v-if="scope.row[column.prop + '_v'] == '1'"
                      style="color: red"
                      >{{ scope.row[column.prop] }}</span
                    >
                    <span v-else>{{ scope.row[column.prop] }}</span>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 分页控件 -->
              <div
                class="pagination-container"
                style="margin: 15px 0; text-align: right"
              >
                <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="pageNum"
                  :page-sizes="[5, 10, 20, 50]"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                  small
                ></el-pagination>
              </div>
            </div>
            <!-- 图表视图 -->
            <div
              v-else-if="viewType === 'chart'"
              class="chart-container"
              key="chart-view"
            >
              <div
                ref="chartContainer"
                style="width: 100%; height: 100%; min-height: 580px"
              ></div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from "echarts";
import tableToExcel from "@/utils/tableToExcel";
import ElTreeSelect from "./TreeSelect.vue";
import { formatDate } from "@/utils/ruoyi";
import {
  getPmDataTree,
  getPmDataList,
} from "@/api/dataResources/waterJcData/jcsection";
export default {
  name: "HydrologicStation",
  components: {
    ElTreeSelect,
  },
  data() {
    return {
      selectedNodeId: "",
      selectedPid: "",
      viewType: "table",
      chartInstance: null,
      treeData: [],
      tableHeight: window.innerHeight - 280,
      radio3: "水源地类型",
      radio2: "最新",
      value1: [],
      value2: [],
      deptName: undefined,
      options: [
        { value: "河流1", label: "河流1" },
        { value: "河流2", label: "河流2" },
        { value: "河流3", label: "河流3" },
      ],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
      },
      tableList: {
        total: 0,
        rows: [],
      },
      dateRange: [],
      ids: [],
      tableOp: [],
      tableData: [], // 完整数据
      paginatedData: [], // 分页后的数据
      pageNum: 1, // 当前页码
      pageSize: 10, // 每页条数
      total: 0, // 总数据量
      defaultProps: {
        children: "children",
        label: "label",
      },
      open: false,
      title: "",
      form: {},
      rules: {
        nickName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "用户名称长度必须介于 2 和 20 之间",
            trigger: "blur",
          },
        ],
        deptId: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.dateRange = this.getDefaultDateRange();
    this.getDeptTree();
  },
  methods: {
    handleViewChange() {
      console.log(">>>视图切换为:", this.viewType);

      if (this.chartInstance) {
        this.chartInstance.dispose();
        this.chartInstance = null;
      }

      if (this.viewType === "chart") {
        this.$nextTick(() => {
          if (this.$refs.chartContainer) {
            this.initChart();
          }
        });
      } else if (this.viewType === "table") {
        this.$nextTick(() => {
          this.paginateData(); // 切换回表格时重新分页
        });
      }
    },
    pageInit() {
      this.getList();
    },
    handleChange(info) {
      console.log("选中的ID:", info.id);
      console.log("选中的PID:", info.pid);
      console.log("完整节点信息:", info.node);

      this.selectedPid = info.pid;
      this.pageNum = 1; // 切换节点后重置页码
      this.pageInit();
    },
    getDefaultDateRange() {
      const firstDay = new Date();
      firstDay.setDate(1);
      const today = new Date();
      return [formatDate(firstDay), formatDate(today)];
    },
    getDeptTree() {
      getPmDataTree().then((response) => {
        this.treeData = response.data;
        console.log(">>>树形数据:", response);
      });
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
    },
    // 每页条数改变
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.paginateData();
    },
    // 当前页码改变
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val;
      this.paginateData();
    },
    handleQuery() {
      this.pageNum = 1; // 搜索后重置页码
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        stationName: "",
        riverName: "",
        longitude: "",
        latitude: "",
        sex: "",
        address: "",
      };
      this.resetForm("form");
    },
    handleExport() {
      tableToExcel.getExcel("#selectTable", "污染源在线监测数据");
    },
    getList() {
      let query = {
        id: this.selectedNodeId,
        pid: this.selectedPid,
        startTime: this.dateRange.length > 0 ? this.dateRange[0] : "",
        endTime: this.dateRange.length > 0 ? this.dateRange[1] : "",
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
      getPmDataList(query).then((res) => {
        console.log(">>>接口返回数据:", res);

        // 模拟接口数据（实际项目中使用res.data）
        // const mockData = {
        //   "tableData": [
        //     {"column1": "2025-10-01 11", "column4": 41, "column3": 29, "column2": 92},
        //     {"column1": "2025-10-02 11", "column4": 23, "column3": 96, "column2": 52},
        //     {"column1": "2025-10-03 11", "column4": 22, "column3": 25, "column2": 49},
        //     {"column1": "2025-10-04 11", "column4": 90, "column3": 2, "column2": 21},
        //     {"column1": "2025-10-05 11", "column4": 56, "column3": 74, "column2": 20},
        //     {"column1": "2025-10-06 11", "column4": 21, "column3": 23, "column2": 95},
        //     {"column1": "2025-10-07 11", "column4": 14, "column3": 51, "column2": 1},
        //     {"column1": "2025-10-08 11", "column4": 81, "column3": 62, "column2": 83},
        //     {"column1": "2025-10-09 11", "column4": 14, "column3": 4, "column2": 4},
        //     {"column1": "2025-10-10 11", "column4": 65, "column3": 71, "column2": 54},
        //     {"column1": "2025-10-11 11", "column4": 9, "column3": 1, "column2": 44},
        //     {"column1": "2025-10-12 11", "column4": 38, "column3": 82, "column2": 26},
        //     {"column1": "2025-10-13 11", "column4": 9, "column3": 82, "column2": 10},
        //     {"column1": "2025-10-14 11", "column4": 7, "column3": 51, "column2": 45},
        //     {"column1": "2025-10-15 11", "column4": 67, "column3": 90, "column2": 84},
        //     {"column1": "2025-10-16 11", "column4": 98, "column3": 63, "column2": 76},
        //     {"column1": "2025-10-17 11", "column4": 74, "column3": 36, "column2": 57},
        //     {"column1": "2025-10-18 11", "column4": 23, "column3": 91, "column2": 22},
        //     {"column1": "2025-10-19 11", "column4": 39, "column3": 26, "column2": 34},
        //     {"column1": "2025-10-20 11", "column4": 27, "column3": 47, "column2": 27},
        //     {"column1": "2025-10-21 11", "column4": 5, "column3": 74, "column2": 70},
        //     {"column1": "2025-10-22 11", "column4": 32, "column3": 99, "column2": 86},
        //     {"column1": "2025-10-23 11", "column4": 46, "column3": 98, "column2": 29},
        //     {"column1": "2025-10-24 11", "column4": 76, "column3": 74, "column2": 38},
        //     {"column1": "2025-10-25 11", "column4": 73, "column3": 28, "column2": 27}
        //   ],
        //   "tableOp": [
        //     {"prop": "column1", "label": "监测时间"},
        //     {"prop": "column2", "label": "总磷(mg/l)"},
        //     {"prop": "column3", "label": "流量(l/s)"},
        //     {"prop": "column4", "label": "总氮(mg/l)"}
        //   ]
        // };

        // 实际项目中使用接口返回数据
        this.tableOp = res.data.tableOp;
        this.tableData = res.data.tableData;
        // 模拟数据测试用
        // this.tableOp = mockData.tableOp;
        // this.tableData = mockData.tableData;

        this.total = this.tableData.length; // 总条数等于数据长度
        this.paginateData(); // 执行分页
      });
    },
    // 分页核心方法：根据当前页码和每页条数截取数据
    paginateData() {
      if (!this.tableData.length) {
        this.paginatedData = [];
        return;
      }
      const startIndex = (this.pageNum - 1) * this.pageSize;
      const endIndex = Math.min(startIndex + this.pageSize, this.total);
      this.paginatedData = this.tableData.slice(startIndex, endIndex);
    },
    initChart() {
      try {
        if (this.chartInstance) {
          this.chartInstance.dispose();
        }

        if (
          !this.$refs.chartContainer ||
          this.tableData.length === 0 ||
          this.tableOp.length === 0
        ) {
          return;
        }

        this.chartInstance = echarts.init(this.$refs.chartContainer);

        const indicatorCols = this.tableOp.filter(
          (col) => col.prop !== "column1"
        );
        const xAxisData = this.tableData.map((row) => row.column1);
        const legendData = indicatorCols.map((col) => col.label);
        const seriesData = indicatorCols.map((col) => ({
          name: col.label,
          type: "line",
          smooth: true,
          lineStyle: { width: 3 },
          data: this.tableData.map((row) => {
            return typeof row[col.prop] === "number"
              ? row[col.prop]
              : Number(row[col.prop]) || 0;
          }),
        }));

        const option = {
          title: {
            text: "污染源监测数据趋势",
            left: "center",
          },
          tooltip: {
            trigger: "axis",
            axisPointer: { type: "shadow" },
          },
          legend: {
            data: legendData,
            top: 30,
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true,
          },
          xAxis: {
            type: "category",
            boundaryGap: false,
            data: xAxisData,
            axisLabel: { rotate: 45 },
          },
          yAxis: {
            type: "value",
            splitArea: { show: true },
          },
          series: seriesData,
        };

        this.chartInstance.setOption(option);

        window.addEventListener("resize", () => {
          this.chartInstance.resize();
        });
      } catch (error) {
        console.error("图表渲染失败:", error);
        this.$message.error("图表加载失败，请重试");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
p {
  margin: 0;
}

img {
  vertical-align: middle;
}

#panel {
  padding-bottom: 40px;
  min-height: calc(100% - 20px);
  margin: 0;

  .pagination-self {
    margin: 20px 0;
    display: flex;
    justify-content: flex-end;
    position: relative;

    .el-pagination__total {
      position: absolute;
      left: 5px;
      color: #409eff;
      font-weight: 600;
      font-size: 15px;
    }
  }

  .refresh-button {
    .el-icon-refresh {
      font-size: 18px;
      line-height: 28px;
    }
  }

  .el-card {
    margin: 10px;
  }

  .queryForm .el-card__body {
    padding: 0 20px !important;
  }

  .queryForm {
    .el-form-item {
      margin: 20px 0 20px 20px;
    }

    .el-form-item:first-child {
      margin-left: 0 !important;
    }

    .el-form-item__label {
      padding-right: 5px;
      color: #555;
    }

    .times {
      .el-form-item__content {
        width: 250px;
      }
    }

    .el-form-item__content {
      min-width: 200px;
    }

    .searchBtnBox {
      display: inline-block;
      margin: 20px 0 20px 20px;
    }
  }

  .pageContent {
    .tabs-list {
      padding-top: 20px;
    }

    .el-tabs__header {
      background: #fff;
    }

    .el-tabs__item {
      border: 1px solid #eee;
      margin: 0;
      border-left: 0;
      background: #fafbfc;
      color: #000;
    }

    .el-tabs__item:first-child {
      margin-left: 20px;
      border-left: 1px solid #eee;
    }

    .is-active {
      border-bottom: 0 !important;
      background: #fff;
      color: #307eff;
    }
  }

  .anjian label {
    padding: 0 !important;
    width: 100px !important;
  }

  .queryForm .el-checkbox {
    margin-right: 10px !important;
    width: auto !important;
  }

  .iszgfc .el-form-item__content {
    width: 120px;
  }
}
</style>
